<script setup lang="ts">
import { ref } from 'vue'
import CustomNavbar from './components/CustomNavbar.vue'
import CategoryPanel from './components/CategoryPanel.vue'
import HotPanel from './components/HotPanel.vue'
import IndexSkeleton from './components/IndexSkeleton.vue'
import { onLoad } from '@dcloudio/uni-app'
import { getHomeBannerAPI, getHomeCategoryAPI, getHomeHotAPI } from '@/services/home'
import type { BannerItem, CategoryItem, HotItem } from '@/types/home'
import { useGuessList } from '@/composables'
const bannerlist = ref<BannerItem[]>([])
const categorylist = ref<CategoryItem[]>([])
const hotList = ref<HotItem[]>([])
const getSYBannerList = async () => {
  const res = await getHomeBannerAPI()
  bannerlist.value = res.result
}
const getSYcategoryList = async () => {
  const res = await getHomeCategoryAPI()
  categorylist.value = res.result
}
const getSYhotList = async () => {
  const res = await getHomeHotAPI()
  hotList.value = res.result
}
//加载中标记
const isLoading = ref(false)
onLoad(async () => {
  isLoading.value = true
  await Promise.all([getSYBannerList(), getSYcategoryList(), getSYhotList()])
  isLoading.value = false
})

// 滚动触底事件
// 猜你喜欢组合式函数
const { guessRef, onScrolltolower } = useGuessList()

// 下拉刷新状态
const isTriggered = ref(false)
// 自定义下拉刷新被触发
const onRefresherrefresh = async () => {
  // 开启动画
  isTriggered.value = true
  // 重置猜你喜欢组件数据
  guessRef.value?.resetData()
  // 加载数据
  await Promise.all([
    getSYBannerList(),
    getSYcategoryList(),
    getSYhotList(),
    guessRef.value?.getMore(),
  ])
  // 关闭动画
  isTriggered.value = false
}
</script>

<template>
  <!-- 自定义导航栏 -->
  <CustomNavbar />
  <!-- 滚动容器 -->
  <scroll-view
    class="scroll-view"
    scroll-y
    @scrolltolower="onScrolltolower"
    refresher-enabled
    @refresherrefresh="onRefresherrefresh"
    :refresher-triggered="isTriggered"
  >
    <IndexSkeleton v-if="isLoading" />
    <template v-else>
      <!-- 自定义轮播图 -->
      <XtxSwiper :list="bannerlist" />
      <!-- 分类面板 -->
      <CategoryPanel :list="categorylist" />
      <!-- 热门推荐 -->
      <HotPanel :list="hotList" />
      <XtxGuess ref="guessRef" />
    </template>
  </scroll-view>
</template>

<style lang="scss">
page {
  background-color: #f7f7f7;
  height: 100%;
  display: flex;
  flex-direction: column;
  scroll-view {
    flex: 1;
  }
}
</style>
